/*
 * Config.cpp
 *
 *  Created on: 15 mei 2013
 *      Author: maarten
 */

#include "Config.hpp"
#include "Logger.hpp"

#include <sstream>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <string>
#include <sstream>
#include <fstream>
#include <iostream>

#define SCONFIGFILE "/home/config.txt"
#define CONFIGSIZE 1000

Config Config::pConfig;

Config::Config() {
	port = 12345;
	nrOfClients = 50;
	exceptExtentions.push_back("txt");
	exceptExtentions.push_back("pdf");
	basePath = "/home/";
	uploadLimit = 1048576; //1048576; //1024*1024 = 1MiB
	IPRange = "145.74.";
}

Config::~Config() {
}

Config& Config::getInstance() {
	return pConfig;
}

int Config::getPort() {
	return port;
}

int Config::getNrOfClients() {
	return nrOfClients;
}

std::vector<std::string> Config::getExtentions() {
	return exceptExtentions;
}

std::string Config::getBasePath() {
	return basePath;
}

int Config::getUploadLimit() {
	return uploadLimit;
}

std::string Config::getWriteIPRange() {
	return IPRange;
}

void Config::writeToFile() {
	std::stringstream temp;
	int config = open(SCONFIGFILE, O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR);
	if (config < 0) {
		Logger::getInstance().log("Can't open to config");
		return;
	}

	temp << "port=" << port << std::endl;
	temp << "nrOfClients=" << nrOfClients << std::endl;
	temp << "IPRange=" << IPRange << std::endl;
	temp << "basePath=" << basePath << std::endl;
	temp << "uploadLimit=" << uploadLimit << std::endl;

	for (std::string extention : exceptExtentions) {
		temp << "extentions=" << extention << std::endl;
	}

	if (write(config, temp.str().c_str(), temp.str().length()) != (unsigned int) temp.str().length()) {
		Logger::getInstance().log("Can't write to logfile");
		return;
	}

	if (close(config) < 0) {
		Logger::getInstance().log("Can't close logfile");
		return;
	}
	return;
}

void Config::readFromFile() {
	std::string line;
	std::ifstream config;
	config.open(SCONFIGFILE);

	exceptExtentions.clear();

	while (getline(config, line)) {
		int split = line.find('=');
		std::string name = line.substr(0, split);
		std::string value = line.substr(split + 1);

		if (!name.compare("port")) {
			port = atoi(value.c_str());
		} else if (!name.compare("nrOfClients")) {
			nrOfClients = atoi(value.c_str());
		} else if (!name.compare("IPRange")) {
			IPRange = value;
		} else if (!name.compare("basePath")) {
			basePath = value;
		} else if (!name.compare("uploadLimit")) {
			uploadLimit = atoi(value.c_str());
		} else if (!name.compare("extentions")) {
			exceptExtentions.push_back(value);
		}
	}

	Logger::getInstance().logImportant("config:");
	std::stringstream log;
	log << port << "*" << nrOfClients << " * " << IPRange << " * " << basePath << " * " << uploadLimit << " * ";

	for (std::string ext : exceptExtentions) {
		log << ext << " * ";
	}
	Logger::getInstance().logImportant(log.str());
}
